package com.ebeitech.auction.view.auction;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.ebeitech.auction.domain.ChatMessage;
import com.ebeitech.auction.domain.dao.ChatMessageDao;
import com.ebeitech.library.constant.MessageConstants;
import com.ebeitech.library.util.Log;
import com.ebeitech.library.util.TimeUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by alice on 2018/1/12.
 */
public class MessageSendService extends Service {

	private Context mContext;
	private ChatMessageDao chatMessageDao;
	private Map<String, Timer> mMap = new HashMap<String, Timer>();
	private AsyncTask<Void, Void, Void> mTask;
	private boolean isNeedRefresh;

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent != null) {
				if (MessageConstants.ACTION_MESSAGE_RECEIVE.equals(intent.getAction())) {
					ChatMessage chatMessage = (ChatMessage) intent.getSerializableExtra(MessageConstants.MESSAGE);
					if (chatMessage != null && mMap.containsKey(chatMessage.getMessageId())) {
						Timer timer = mMap.get(chatMessage.getMessageId());
						if (timer != null) {
							timer.cancel();
						}
						mMap.remove(chatMessage.getMessageId());

						if (mMap.isEmpty() && mTask != null && mTask.getStatus() == AsyncTask.Status.RUNNING) {
							mTask.cancel(true);
						}
					}
				}
			}
		}
	};

	@Override
	public void onCreate() {
		super.onCreate();
		mContext = getApplicationContext();
		registerBroadCast();
		Log.i("MessageSendService", "MessageSendService onCreate");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i("MessageSendService", "MessageSendService onStartCommand");
		if (mTask != null && mTask.getStatus() == AsyncTask.Status.RUNNING) {
			isNeedRefresh = true;
		} else {
			isNeedRefresh = false;
			initMessage();
		}
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mBroadcastReceiver);
	}

	private void initMessage() {
		chatMessageDao = ChatMessageDao.getInstance();
		mTask = new AsyncTask<Void, Void, Void>() {
			@Override
			protected Void doInBackground(Void... params) {
				String selection = "messageState='" + ChatMessage.MESSAGE_STATE_SENDING + "'";
				List<ChatMessage> chatMessages = chatMessageDao.getChatMessageListWithSelection(selection);
				String currentTime = TimeUtil.getCurrentTime();
				for (final ChatMessage chatMessage : chatMessages) {
					String sendFailTime = TimeUtil.getTimeWithDiff(TimeUtil.getDateToString(new Date(Long.valueOf(chatMessage.getSendTime()))), 1, TimeUtil.UNIT_MINUTE);
					if (currentTime.compareTo(sendFailTime) >= 0) {
						chatMessage.setSendFail(false);
						ChatMessageDao.getInstance().insertOrUpdate(chatMessage);

						Intent intent = new Intent(MessageConstants.ACTION_MESSAGE_SEND_FAILURE);
						intent.putExtra(MessageConstants.MESSAGE, chatMessage);
						mContext.sendBroadcast(intent);
					} else {
						Timer timer = new Timer();
						mMap.put(chatMessage.getMessageId(), timer);
						timer.schedule(new TimerTask() {
							@Override
							public void run() {
								chatMessage.setSendFail(false);
								ChatMessageDao.getInstance().insertOrUpdate(chatMessage);

								Intent intent = new Intent(MessageConstants.ACTION_MESSAGE_SEND_FAILURE);
								intent.putExtra(MessageConstants.MESSAGE, chatMessage);
								mContext.sendBroadcast(intent);
							}
						}, new Date(TimeUtil.getTimeMillis(sendFailTime)));
					}
				}
				return null;
			}

			@Override
			protected void onProgressUpdate(Void... values) {
				super.onProgressUpdate(values);
				if (isNeedRefresh) {
					initMessage();
				}
			}
		};
		mTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private void registerBroadCast() {
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(MessageConstants.ACTION_MESSAGE_RECEIVE);
		registerReceiver(mBroadcastReceiver, myIntentFilter);
	}

	@Nullable
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
}
